import { getPersonInfo, login } from '@/api/user'
import { getToken, removeToken, setToken, getPhone, removePhone, setPhone } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    baseInfo: {
      name: '', birthday: '', gender: '', age: '',
      email: '', id_card: '', school: '', education: '',
      major: '', Political: '', Home_address: '', user_image: '',
      Id_address: '', mobile: getPhone()
    },
    baseKaoshiInfo: {},
    allKaoshiInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_BASEINFO: (state, payload) => {
    state.baseInfo = payload
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getBaseInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getPersonInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('个人基础信息获取失败')
        }
        commit('SET_BASEINFO', data)
        sessionStorage.removeItem('baseInfo')
        sessionStorage.setItem('baseInfo', JSON.stringify(data))
        setPhone(data.phone)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  freshBaseInfo({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_BASEINFO', JSON.parse(sessionStorage.getItem('baseInfo')))
      resolve()
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      removePhone()
      sessionStorage.clear()
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removePhone()
      sessionStorage.clear()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

